package com.chaos.auth.service;

import cn.hutool.core.util.ObjectUtil;
import com.chaos.framework.model.dto.ID;
import com.chaos.framework.model.dto.page.PageList;
import com.chaos.framework.model.dto.page.PageQueryDto;
import com.chaos.framework.model.entity.Table;
import com.chaos.framework.model.helper.ConvertHelper;
import com.chaos.framework.model.helper.PageHelper;
import com.chaos.auth.entity.TUser;
import com.chaos.auth.api.data.TUserData;
import com.chaos.auth.mapper.TUserMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @author Jacky.Cui
 * @since 2024-11-13
 */
@Slf4j
@Component
public class TUserService extends ServiceImpl<TUserMapper, TUser> {

    public ID insertModel(TUserData data) {
        TUser entity = ConvertHelper.convert(data, TUser.class);
        return save(entity) ? new ID(entity.getId()) : null;
    }

    public boolean deleteModel(ID data) {
        return removeById(data.getId());
    }

    public boolean updateModelByID(TUserData data) {
        TUser entity = ConvertHelper.convert(data, TUser.class);
        return update(entity, new UpdateWrapper<TUser>().eq(Table.ID, data.getId()));
    }

    public TUserData selectByID(ID data) {
        return ConvertHelper.convert(getOne(new QueryWrapper<TUser>().eq(Table.ID, data.getId())), TUserData.class);
    }

    public List<TUserData> selectByData(TUserData data) {
        QueryWrapper<TUser> query = new QueryWrapper<>();
        query.lambda()
                .eq(ObjectUtil.isNotEmpty(data.getWxOpenId()), TUser::getWxOpenId, data.getWxOpenId())
                .eq(ObjectUtil.isNotEmpty(data.getPhone()), TUser::getPhone, data.getPhone())
                .eq(ObjectUtil.isNotEmpty(data.getAliOpenId()), TUser::getAliOpenId, data.getPhone())
        ;
        query.orderByDesc(Table.ID);
        return ConvertHelper.convert(list(query), TUserData.class);
    }

    public PageList<TUserData> selectByPage(PageQueryDto<TUserData> pageData) {
        TUserData data = pageData.getData();
        QueryWrapper<TUser> query = new QueryWrapper<>();
        query.lambda()
                .eq(ObjectUtil.isNotEmpty(data.getWxOpenId()), TUser::getWxOpenId, data.getWxOpenId())
                .eq(ObjectUtil.isNotEmpty(data.getPhone()), TUser::getPhone, data.getPhone())
                .eq(ObjectUtil.isNotEmpty(data.getAliOpenId()), TUser::getAliOpenId, data.getPhone())
        ;
        query.orderByDesc(Table.ID);
        return PageHelper.pageList(page(PageHelper.page(pageData), query), TUserData.class);
    }

}
